<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    showFooter :width="width" 
    :title="getTitle" 
    @ok="handleSubmit" 
    destroyOnClose
  >
    <Tabs>
      <TabPane tab="基础信息" key="goods_base">
        <GoodsBaseInfoTab v-bind="goodsData" ref="goodsBaseInfoTabRef"/>
      </TabPane>

      <TabPane tab="商品详情" key="goods_detail">
        <MyRichTextEditor v-model:value="goodsData.detailContent"/>
      </TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs } from 'vue';
import { Tabs } from 'ant-design-vue';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { saveOrUpdateGoods, getGoods } from './goods.api';
import { MyRichTextEditor } from '/@/components/My/WangEditor/index';
import { useAdapt } from '/@/hooks/system/useAutoAdapt.ts';
import { GoodsState } from './type';
import { useMessage } from '/@/hooks/web/useMessage';
import GoodsBaseInfoTab from './GoodsBaseInfoTab.vue'
const TabPane = Tabs.TabPane
const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const { width } = useAdapt({ xl: 1000, lg: 1000, md: 1000, sm: 1000, xs: 1000});
const attrs = useAttrs()
const goodsBaseInfoTabRef = ref()
const goodsData = ref<GoodsState>({
  id: '',
  detailContent: undefined,
  skuList: [],
  specList: [],
  isUpdate: false
})

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ loading: true });
  try {
    const isUpdate = !!data?.isUpdate;
    const record = isUpdate ? await getGoods({id: data.record?.id}) : {}
    const images = record.images && record.images.join(',')
    goodsData.value = {isUpdate, ...record, images }
    console.log("goods data: ", goodsData.value);
  } finally {
    setDrawerProps({ loading: false });
  }
});

const getTitle = computed(() => (!unref(goodsData.value?.isUpdate) ? '新增商品' : '编辑商品'));

async function handleSubmit() {
  try {
    const values = await goodsBaseInfoTabRef.value.getData()
    console.log('submit data', values);
    
    setDrawerProps({ confirmLoading: true });
    await saveOrUpdateGoods({ 
      ...values, 
      id: goodsData.value.id,
      goodsTypes: values.goodsTypes.split(','),
      images: (values.images && values.images === '') ? [] : values.images.split(','),
      detailContent: goodsData.value.detailContent
    }, unref(goodsData.value?.isUpdate))
    closeDrawer();
    createMessage.success(`${getTitle.value}成功`)
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

</script>

<style lang="less">
.goods-spec-type {
  margin-top: 10px;
  margin-bottom: 10px;
}

</style>

